package com.example.todolist.view;

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.example.todolist.R
import com.example.todolist.database.model.CategoryEntity
import com.example.todolist.databinding.CategoryItemBinding
import com.example.todolist.entity.CategoryDetail

class CategoryAdapter(private val context: Context, private val onSelCategory: (Int) -> Unit) :
    ListAdapter<CategoryDetail, CategoryAdapter.CategoryHolder>(CategoryDiffCallback()) {
    private var selPostion = 0

    inner class CategoryHolder(val binding: CategoryItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
        val tvCategory: TextView = binding.categoryItem
        fun bind(category: CategoryDetail) {
            tvCategory.text = category.categoryName
            tvCategory.setTextColor(Color.GRAY)
            if (selPostion == adapterPosition) {
                tvCategory.setTextColor(context.resources.getColor(R.color.deepblue))
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryHolder {
        val binding = CategoryItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return CategoryHolder(binding)
    }

    override fun onBindViewHolder(holder: CategoryHolder, position: Int) {
        val category = getItem(position)
        holder.bind(category)
        holder.tvCategory.setOnClickListener {
            onSelCategory(category.categoryId)

            val oldPos = selPostion
            selPostion = holder.adapterPosition

            notifyItemChanged(oldPos)
            notifyItemChanged(selPostion)
        }
    }

    // 用于计算列表差异的回调类
    class CategoryDiffCallback : DiffUtil.ItemCallback<CategoryDetail>() {
        override fun areItemsTheSame(oldItem: CategoryDetail, newItem: CategoryDetail): Boolean {
            return oldItem.categoryId == newItem.categoryId // 假设CategoryVO有唯一标识id
        }

        override fun areContentsTheSame(oldItem: CategoryDetail, newItem: CategoryDetail): Boolean {
            return oldItem == newItem // 基于内容的完整比较
        }
    }
}
